package com.terren.spider.util.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;



public class RandomUA {
	private static ArrayList<String> uaList;
	//private static boolean loadUa = false;
    private static final String WEB_UA_FILE = CommonUtil.getProjectPath(RandomUA.class)+"/data/web_ua.txt";
    private static final String MOBILE_UA_FILE = CommonUtil.getProjectPath(RandomUA.class)+"/data/mobile_ua.txt";
	
	public static String getRandomWebUa() {
		//if(!loadUa)
			uaList = importUserAgent(WEB_UA_FILE);
		int n = (int)Math.floor(Math.random() * uaList.size());
		int i = 0;
		String randomUa = "";
		for(String ua : uaList) {
			if(i == n) {
				randomUa = ua;
				break;
			}
			i++;
		}
		return randomUa;
	}
	public static String getRandomMobileUa() {
		//if(!loadUa)
			uaList = importUserAgent(MOBILE_UA_FILE);
		int n = (int)Math.floor(Math.random() * uaList.size());
		int i = 0;
		String randomUa = "";
		for(String ua : uaList) {
			if(i == n) {
				randomUa = ua;
				break;
			}
			i++;
		}
		return randomUa;
	}

	private static ArrayList<String> importUserAgent(String filePath){
		ArrayList<String> uaLs = new ArrayList<String>();
		try{
			File file = new File(filePath);
	    	InputStreamReader fr = new InputStreamReader( new FileInputStream(file),"GBK"); 
			BufferedReader br = new BufferedReader(fr);
			String str = br.readLine();
			while(str != null && str.length() > 0) {
				uaLs.add(str);
				str = br.readLine();
			}
			br.close();
			fr.close();
		//	loadUa = true;
			LogUtil.logger.info("Reading " + uaLs.size() + " UserAgent.");
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return uaLs;
	}
}
